<template>
    <div class="upload-container">
        <el-button
            v-if="showButton"
            :style="{background:color,borderColor:color}"
            icon="el-icon-upload"
            size="mini"
            type="primary"
            @click=" dialogVisible=true"
        >上传图片</el-button>
        <el-dialog :visible.sync="dialogVisible" append-to-body="true">
            <el-upload
                :multiple="true"
                :file-list="fileList"
                :show-file-list="true"
                :on-remove="handleRemove"
                :on-success="handleSuccess"
                :before-upload="beforeUpload"
                class="editor-slide-upload"
                action="https://httpbin.org/post"
                list-type="picture-card"
            >
                <el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
            </el-upload>
            <el-button @click="dialogVisible = false" icon="el-icon-close">取 消</el-button>
            <el-button type="primary" @click="handleSubmit" icon="el-icon-check">确 定</el-button>
            <span style="color:red;float: right;">{{ picTip }}</span>
        </el-dialog>
    </div>
</template>

<script>
// import { getToken } from 'api/qiniu'

export default {
    name: "EditorSlideUpload",
    props: {
        color: {
            type: String,
            default: "#1890ff"
        },
        showButton: {
            type: Boolean,
            default: true
        },
        picTip: {
            type: String,
            default: ''
        },
        limitFileSize: {
            type: Boolean,
            default: true
        }
    },
    data() {
        return {
            dialogVisible: false,
            listObj: {},
            fileList: [],
            fileMsg: '',
            flag: false
        };
    },
    methods: {
        checkAllSuccess() {
            return Object.keys(this.listObj).every(
                item => Object.keys(this.listObj[item]).length>0 && this.listObj[item].hasSuccess
            );
        },
        handleSubmit() {
            if (this.flag) {
                const arr = Object.keys(this.listObj).map(v => this.listObj[v]);
                if (!this.checkAllSuccess()) {
                    this.$message.error( "网络环境异常，请等待或重新上传！" );
                    return;
                }
                this.$emit("successCBK", arr);
                this.listObj = {};
                this.fileList = [];
                this.dialogVisible = false;
                this.flag = false
            }else{
                this.$message.error( "图片尚未加载成功，请耐心等待！" );
            }
        },
        handleSuccess(response, file) {
            this.fileMsg = response.url
            if (!this.fileMsg) {
                this.flag = false
            }
            this.flag = true
            const uid = file.uid;
            const objKeyArr = Object.keys(this.listObj);
            for (let i = 0, len = objKeyArr.length; i < len; i++) {
                if (this.listObj[objKeyArr[i]].uid === uid) {
                    this.listObj[objKeyArr[i]].url = response.files.file;
                    this.listObj[objKeyArr[i]].hasSuccess = true;
                    return;
                }
            }
        },
        handleRemove(file) {
            const uid = file.uid;
            const objKeyArr = Object.keys(this.listObj);
            for (let i = 0, len = objKeyArr.length; i < len; i++) {
                if (this.listObj[objKeyArr[i]].uid === uid) {
                    delete this.listObj[objKeyArr[i]];
                    return;
                }
            }
        },
        beforeUpload2(file) {
            let isJPG = false;
            const isLt10M = file.size / 1024 / 1024 < 10;

            if (file.type === "image/jpeg") {
                isJPG = true;
            }
            if (file.type === "image/png") {
                isJPG = true;
            }
            if (file.type === "image/jpg") {
                isJPG = true;
            }

            if (!isJPG) {
                this.$message.error("上传头像图片只能是 JPG或png 格式!");
                return isJPG;
            }
            if (!isLt10M) {
                this.$message.error("上传头像图片大小不能超过 10MB!");
                return isLt10M;
            }
            const _self = this;
            const _URL = window.URL || window.webkitURL;
            const fileName = file.uid;
            this.listObj[fileName] = {};
            return new Promise((resolve, reject) => {
                const img = new Image();
                img.src = _URL.createObjectURL(file);
                img.onload = function() {
                    _self.listObj[fileName] = {
                        hasSuccess: false,
                        uid: file.uid,
                        width: this.width,
                        height: this.height
                    };
                };
                resolve(true);
            });
        },

        // add by quanwei
        beforeUpload(file) {
            let isJPG = false;
            const isLt10M = file.size / 1024 / 1024 < 10;
            if (file.type === "image/jpeg") {
                isJPG = true;
            }
            if (file.type === "image/png") {
                isJPG = true;
            }
            if (file.type === "image/jpg") {
                isJPG = true;
            }
            if (!isJPG) {
                this.$message.error("上传图片格式为 jpg或png !");
                return isJPG;
            }
            const _self = this;
            const fileName = file.uid;
            this.listObj[fileName] = {};
            const isSize = new Promise(function(resolve, reject) {
                let width = 550;
                let height = 550;
                let _URL = window.URL || window.webkitURL;
                let img = new Image();
                img.onload = function() {
                    let valid = img.width <= width && img.height <= height;
                    valid ? resolve() : reject();
                    if(valid){
                        _self.listObj[fileName] = {
                            hasSuccess: false,
                            uid: file.uid,
                            width: img.width ,
                            height: img.height
                        };
                    }
                    if (!this.limitFileSize) {
                        _self.listObj[fileName] = {
                            hasSuccess: true,
                            uid: file.uid,
                            width: img.width ,
                            height: img.height
                        }; 
                    }
                }
                img.src = _URL.createObjectURL(file);
            }).then(() => {
                return file;
            }, () => {
                if (this.limitFileSize) {
                    this.$message.error('图片尺寸不能大于550 x 550');
                    return Promise.reject();
                }
            });
            if (!isLt10M) {
                if (this.limitFileSize) {
                    this.$message.error('图片尺寸不能大于550 x 550，且大小不可超过10MB!');
                } else {
                    this.$message.error('图片大小不可超过10MB!');
                }
                return isLt10M;
            }
            if(isJPG && isLt10M){
                delete this.listObj[file.uid];
                return isSize;
            } else {
                delete this.listObj[file.uid];
                return isJPG && isLt10M;
            }
        }
    }
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.editor-slide-upload {
    margin-bottom: 20px;
    ::v-deep .el-upload--picture-card {
        width: 100%;
    }
}
</style>
